import sys
import os

from win32com.client import gencache
from win32com.client import constants

# 接收外来参数
args = sys.argv
if len(args) <= 1:
    print("无输入参数！")
    sys.exit()

# Word转PDF函数
def wordToPdf(wordPath, pdfPath):
    """
        word转pdf
        :param wordPath: word文件路径
        :param pdfPath:  生成pdf文件路径
        """
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(wordPath, ReadOnly=1)
    doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    word.Quit(constants.wdDoNotSaveChanges)

# 遍历传入的参数
for i in range(len(args)):
    if i == 0:
        continue
    # Word文件路径
    wordPath = args[i]
    print(wordPath,end="\n")

	pdfPath = ""
    if wordPath.endswith(".docx"):
        pdfPath = args[i].replace(".docx", ".pdf")
    elif wordPath.endswith(".doc"):
        pdfPath = args[i].replace(".doc", ".pdf")
    else:
        print("文件格式不符！")

    print(pdfPath,end="\n")

    # pdf文件是否存在
    if os.path.exists(pdfPath):
        print("此文件已存在，跳过")
        continue

    try:
        # 开始转换
        wordToPdf(wordPath, pdfPath)
    except Exception as e:
        print("程序出现异常：",e)
        sys.exit()
